package com.tyc.mb.handler;

import com.tyc.mb.exception.BaseException;
import com.tyc.mb.model.response.CommonResult;
import com.tyc.mb.model.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.WebExchangeBindException;

/**
 * 类描述 异常统一处理类
 *
 * @author tyc
 * @version 1.0
 * @date 2021-10-27 14:36:11
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * webflux下参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(WebExchangeBindException.class)
    public CommonResult webExchangeBindException(WebExchangeBindException e) {
        String msg = e.getBindingResult().getFieldError().getDefaultMessage();
        return  CommonResult.failed(ResultCode.PARAM_CHECK_FAILED,msg);
    }

    @ExceptionHandler(BindException.class)
    public CommonResult bindException(BindException e) {
        String msg = e.getBindingResult().getFieldError().getDefaultMessage();
        return  CommonResult.failed(ResultCode.PARAM_CHECK_FAILED,msg);
    }


    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public CommonResult baseException(BaseException baseException) {
        int code = baseException.getCode();
        String msg = baseException.getMsg();
        log.error("baseException:{},{}", code, msg);
        return new CommonResult(code, msg);
    }



    @ExceptionHandler(Throwable.class)
    public CommonResult exception(Throwable throwable) {
        throwable.printStackTrace();
        return  CommonResult.failed();
    }
}
